package com.wjbgn.test.service;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.wjbgn.test.util.kafka.producer.KafkaProducer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * @description： 订单服务
 * @author：weirx
 * @date：2022/1/27 10:30
 * @version：3.0
 */
@Slf4j
@Component
public class OrderServiceImpl {

    @Autowired
    private KafkaProducer kafkaProducer;

    @Value("${server.url.user}")
    private String userServerUrl;

    @Value("${server.url.goods}")
    private String goodsServerUrl;

    private final static String GOODS_INFO_GET_BY_ID = "/goods/info/getById";

    private final static String USER_INFO_GET_BY_ID = "/user/info/getById";

    private final static String ORDER_SAVE = "/order/save";

    /**
     * description:
     * 调用用户服务，获取用户信息
     * 使用获取的用户信息去查询并绑定商品信息
     * 使用用户和商品信息进行下单
     *
     * @return: void
     * @author: weirx
     * @time: 2022/1/27 10:31
     */
    public void order() {
        // 随机查询一个用户
        String user = HttpUtil.get(userServerUrl + USER_INFO_GET_BY_ID + "?id=" + RandomUtil.randomLong(1L, 100000L));
        Long userId = JSONObject.parseObject(user).getJSONObject("data").getLong("id");

        // 随机获得一个商品
        String goods = HttpUtil.get(goodsServerUrl + GOODS_INFO_GET_BY_ID + "?id=" + RandomUtil.randomLong(1L, 10000L));
        Long goodsId = JSONObject.parseObject(goods).getJSONObject("data").getLong("id");

        // 创建订单
        Map<String, Object> map = new HashMap<>(4);
        map.put("userId", userId);
        map.put("goodsId", goodsId);
        map.put("goodsNum", RandomUtil.randomInt(1, 5));
        kafkaProducer.send("rob-necessities-order",JSONObject.toJSONString(map));
    }
}
